/* 拖拽释放提示 */
<template>
	<div
		class="popup upload-model"
		@click.self="$emit('close')"
	>
		<div
			v-if="uploadList.length===0"
			class="content upload-tip"
		>
			将文件拖动到此处，或者
			<ChooseFile @change="uploadFile">
				<span class="select-file">点击上传</span>
			</ChooseFile>
			（大于50M的文件会被过滤）
		</div>
		<div
			v-else
			class="content upload-list"
		>
			<div
				class="file"
				v-for="(file,i) in uploadList"
				:key="i"
			>
				<!-- 文件名，大小 -->
				<header>
					<div class="name">{{file.name}}</div>
					<div class="size">{{file.size}}</div>
				</header>
				<!-- 加载进度和状态 -->
				<footer>
					<el-progress
						:percentage="file.progress"
						:stroke-width="14"
						:status="file.status"
					/>
				</footer>
			</div>
		</div>
	</div>
</template>

<script>
import { getPublicUploadSign } from '@exploit/api/file'
import { renderSize, cosUpload } from '@/utils/file'
import { basePath, getFileTime } from '@exploit/utils/file'

export default {
  props: {
    url: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      uploadList: []
    }
  },
  mounted() {
    this.setListen(true)
  },
  beforeDestroy() {
    this.setListen(false)
  },
  methods: {
    /**
     * 初始化浏览器监听事件
     */
    setListen(add = true) {
      const prevent = (e) => {
        e.preventDefault()
      }
      const drop = (e) => {
        this.uploadFile(Array.from(e.dataTransfer.files))
      }

      if (add) {
        document.addEventListener('dragenter', prevent)
        document.addEventListener('dragleave', prevent)
        document.addEventListener('drop', prevent)
        document.addEventListener('dragover', prevent)
        document.querySelector('.upload-tip') && document.querySelector('.upload-tip').addEventListener('drop', drop)
      } else {
        document.removeEventListener('drop', prevent)
        document.removeEventListener('dragleave', prevent)
        document.removeEventListener('dragenter', prevent)
        document.removeEventListener('dragover', prevent)
        document.querySelector('.upload-tip') && document.querySelector('.upload-tip').removeEventListener('drop', drop)
      }
    },
    /**
     * 上传文件
     * @param {file[]} files 选择的文件数组
     */
    async uploadFile(files) {
      this.setListen(false)
      this.uploadList = files.filter(file => file.size < 50000000).map(item => {
        return {
          name: item.name,
          size: renderSize(item.size),
          status: '',
          progress: 0,
          source: item
        }
      })
      /* 开始上传 */
      await Promise.all(this.uploadList.map(async(item) => {
        const name = `/${ basePath }${ this.url }${ getFileTime() }-${ item.name }`

        const sign = await getPublicUploadSign(name)

        return cosUpload(item.source, sign.data, (progress) => {
          item.progress = progress
        })
          .then(() => {
            item.status = 'success'
          })
          .catch(() => {
            item.status = 'exception'
          })
      }))
      this.$emit('uploadFinish')
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-model {
  background-color: rgba($color: #ffffff, $alpha: 0.5) !important;

  .content {
    width: 600px;
    height: 400px;
    border-radius: $radiusMiddle;
    box-shadow: $shadow1;
    transform: translate(-60%, -60%);
  }

  .upload-tip {
    line-height: 400px;
    text-align: center;

    .select-file {
      color: $blue;
      cursor: pointer;
    }
  }

  .upload-list {
    overflow-y: auto;

    .file {
      padding-bottom: 5px;
      margin-bottom: 15px;

      header {
        display: flex;
        margin: 0 10px 5px 0;
        font-size: $sSmall;

        .name {
          flex: 1;
        }
      }

      footer {
        ::v-deep .el-progress__text {
          font-size: $sSmall !important;
        }

        ::v-deep .el-icon-circle-check {
          font-size: $sLarge !important;
        }
      }
    }
  }
}
</style>
